<script lang="ts" setup>
import qs from 'qs'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { reactive, ref } from 'vue'
import { GetData, GetExcelData, PostCopy, PostListingDelist, patchListInventory, patchListSort } from '@/api/modules/merchandiseControl.ts'
// import PageNumber from '@/store/modules/PageNumberCache'
import storage from '@/utils/storage'
import GetCacheData from '@/store/modules/NewPageCache'

const router = useRouter()
const imgDomain = 'https://img1.eprhan.cc'
// const PageNumberCache = PageNumber()
const cacheData = GetCacheData()
let PageNum = cacheData.GetCacheData('MerchandiseControl').currentPage

// 导航栏
// const activeIndex = ref(true)

// 查询表单
const findFrom = ref({
  ...(cacheData.GetCacheData('MerchandiseControl').fromData),
})

function handleSelect(key: string) {
  key === 'true' ? findFrom.value.IsActive = true : findFrom.value.IsActive = false
  cacheData.SetCacheData('MerchandiseControl', PageNum, cacheData.GetCacheData('MerchandiseControl').currentSize, findFrom.value)
  GetDataList(1, cacheData.GetCacheData('MerchandiseControl').currentSize)
}

// 商品类型
const merchandiseTypeArr = [
  { value: '~', label: '全部' },
  { value: 1, label: '正常商品' },
  { label: '积分商品', value: 2 },
  { label: '秒杀商品', value: 3 },
  { label: '派样秒杀', value: 4 },
  { label: '拼团商品', value: 5 },
  { value: 6, label: '援疆商品' },
  { value: 7, label: '品牌官商品' },
]
// 加载
const loading = ref(false)
const total = ref(0) // 总数据数

// 数据列表
const dataList = reactive({
  list: [],
})

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('MerchandiseControl').currentSize)
  cacheData.SetCacheData('MerchandiseControl', PageNum, cacheData.GetCacheData('MerchandiseControl').currentSize, findFrom.value)
}

// 列表选中
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref([])
function handleSelectionChange(val: any) {
  multipleSelection.value = val.map((item: any) => {
    return item.productId
  })
}

// 批量上下架
function ListingDelist() {
  const params = {
    productIdList: multipleSelection.value,
    isActive: !findFrom.value.IsActive,
  }
  PostListingDelist(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('操作成功。')
      GetDataList(cacheData.GetCacheData('MerchandiseControl').currentPage, cacheData.GetCacheData('MerchandiseControl').currentSize)
    }
    else {
      ElMessage.error(`操作失败。${res.errors}`)
    }
  })
}
// 单个商品上下架
function SingleListingDelist(productId: number) {
  const params = {
    productIdList: [productId],
    isActive: !findFrom.value.IsActive,
  }
  ElMessageBox.confirm(
  `是否确认要${findFrom.value.IsActive ? '下架' : '上架'}该商品？`,
  '提示',
  {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  },
  )
    .then(() => {
      PostListingDelist(params).then((res: any) => {
        if (res.succeeded) {
          ElMessage.success('操作成功。')
          GetDataList(cacheData.GetCacheData('MerchandiseControl').currentPage, cacheData.GetCacheData('MerchandiseControl').currentSize)
        }
        else {
          ElMessage.error(`操作失败。${res.errors}`)
        }
      })
    })
}

// 获取数据
async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    IsActive: findFrom.value.IsActive,
    ...(findFrom.value.productName && { ProductName: findFrom.value.productName }),
    ...(findFrom.value.productId && { productId: findFrom.value.productId }),
    ...(findFrom.value.storeSelect && { StoreSelect: findFrom.value.storeSelect }),
    ...(findFrom.value.classifySelect && { ClassifySelect: findFrom.value.classifySelect }),
    ...((findFrom.value.flag && (findFrom.value.flag as string | number) !== '~') && { FlagList: [findFrom.value.flag] }),
  }
  const parameter = qs.stringify(params)
  await GetData(parameter).then((res: any) => {
    // console.log(res.data.items)
    if (res.succeeded) {
      dataList.list = res.data.items
      total.value = res.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`获取数据失败。${res.errors}`)
      loading.value = false
    }
  }).catch(() => {
    ElMessage.error('获取数据失败。')
    loading.value = false
  })
}

// 修改排序
function SortModification(message: any) {
  const params = {
    productId: message.row.productId,
    sortNum: message.row.sortTag,
  }
  patchListSort(params).then((res) => {
    if (res.data) {
      ElMessage.success('修改成功。')
    }
    else {
      ElMessage.error('修改失败。')
      GetDataList()
    }
  })
}
// 修改库存
function InventoryModification(message: any) {
  const params = {
    productId: message.row.productId,
    inventory: message.row.productNums,
  }
  patchListInventory(params).then((res) => {
    if (res.data) {
      ElMessage.success('修改成功。')
    }
    else {
      ElMessage.error('修改失败。')
      GetDataList()
    }
  })
}

function Copy(productId: number) {
  ElMessageBox.confirm(
    '是否复制该商品',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      PostCopy(productId).then((res: any) => {
        if (res.succeeded) {
          ElMessage.success('复制成功。')
          GetDataList()
          ElMessageBox.confirm(
            '是否编辑该商品',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            },
          )
            .then(() => {
              router.push({
                name: 'merchandiseControlDetail',
                query: {
                  id: res.data,
                },
              })
            })
        }
        else {
          ElMessage.error(`复制失败。${res.errors}`)
        }
      })
    })
}

// 编辑
function Redact(productId: number) {
  router.push({
    name: 'merchandiseControlDetail',
    query: {
      id: productId,
    },
  })
}

// 跳转积分
function MemberProduct(productId: number, isScoreProduct: boolean) {
  router.push({
    name: 'memberproductDetail',
    query: {
      productId,
      type: isScoreProduct ? '1' : '0',
    },
  })
}

function SkipPintuan(productId: number) {
  router.push({
    name: 'pintuanIndex',
    query: {
      productId,
    },
  })
}

// 导出商品销量
const excelDialog = ref(false)
const excelForm = reactive({
  // BrandId: '',
  // ProductId: '',
  // ProductName: '',
  // IsActive: true,
  FlagList: [],
  ActiveTime: [],
  OrderTime: [],
})
function OpenExcelDialog() {
  // excelForm.BrandId = ''
  // excelForm.ProductId = ''
  // excelForm.ProductName = ''
  // excelForm.IsActive = true
  excelForm.FlagList = []
  excelForm.ActiveTime = []
  excelForm.OrderTime = []
  excelDialog.value = true
}

async function GetExcel() {
  const params: any = {
    ...(findFrom.value.BrandId !== '~' && { BrandId: findFrom.value.BrandId }),
    ...(findFrom.value.productName && { ProductName: findFrom.value.productName }),
    ...(findFrom.value.productId && { productId: findFrom.value.productId }),
    IsActive: findFrom.value.IsActive,
    ...((findFrom.value.flag !== '~') && { FlagList: [findFrom.value.flag] }),
    ...(excelForm.ActiveTime.length !== 0 && { ActiveStartTime: excelForm.ActiveTime[0], ActiveEndTime: excelForm.ActiveTime[1] }),
    ...(excelForm.OrderTime.length !== 0 && { OrderStartTime: excelForm.OrderTime[0], OrderEndTime: excelForm.OrderTime[1] }),
  }
  const parameter = qs.stringify(params)
  try {
    // console.log(parameter)

    const response: any = await GetExcelData(parameter)
    // console.log(response)

    const a = document.createElement('a')
    const binaryData = []
    binaryData.push(response)
    a.href = window.URL.createObjectURL(
      new Blob(binaryData, {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=UTF-8',
      }),
    )
    a.download = (storage.local.get('fileName') as string)
    storage.local.remove('fileName')
    a.click()
    URL.revokeObjectURL(a.href)
    excelDialog.value = false
  }
  catch (error) {
    // 请求失败处理
    console.error(error)
  }
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('MerchandiseControl', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('MerchandiseControl').currentSize)
  cacheData.SetCacheData('MerchandiseControl', val, cacheData.GetCacheData('MerchandiseControl').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('MerchandiseControl').currentPage || 1
})

onMounted(async () => {
  GetDataList(cacheData.GetCacheData('MerchandiseControl').currentPage, cacheData.GetCacheData('MerchandiseControl').currentSize)
})
</script>

<template>
  <div>
    <el-menu :default-active="String(findFrom.IsActive)" mode="horizontal" @select="handleSelect">
      <el-menu-item index="true">
        出售中的商品
      </el-menu-item>
      <el-menu-item index="false">
        仓库中的商品
      </el-menu-item>
    </el-menu>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="商品名称">
                <el-input v-model="findFrom.productName" placeholder="请输入商品名称" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="商品ID">
                <el-input v-model="findFrom.productId" placeholder="请输入商品ID" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="商品类型">
                <el-select v-model="findFrom.flag" placeholder="请选择订单状态">
                  <el-option v-for="item in merchandiseTypeArr" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5" style="display: flex; justify-content: space-between;">
        <el-button @click="ListingDelist">
          批量{{ findFrom.IsActive ? '下架' : '上架' }}
        </el-button>
        <el-button type="success" @click="OpenExcelDialog">
          导出商品销量
        </el-button>
      </div>
      <ElTable ref="multipleTableRef" v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column align="center" prop="productId" label="商品ID" width="100" />
        <el-table-column align="center" prop="cdnqrCodeBGPicUrl" label="商品图片" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.cdnProductPhotoPic" />
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="productName" label="商品名称" width="470" show-overflow-tooltip />
        <el-table-column align="center" prop="salePrice" label="价格" width="100" />
        <el-table-column align="center" prop="marketPrice" label="市场价" width="100" />
        <el-table-column align="center" prop="baseSaleCount" label="销量" width="100">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="`${scope.row.productSaleCount}`"
              placement="top"
            >
              {{ scope.row.baseSaleCount + scope.row.productSaleCount }}
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="activeTime" label="上架时间" width="200" />
        <el-table-column align="center" prop="productNums" label="库存" fixed="right" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.productNums" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="InventoryModification(scope)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sortTag" label="排序" fixed="right" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.sortTag" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="SortModification(scope)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="280">
          <template #default="scope">
            <div class="table-button">
              <el-button type="success" @click="Copy(scope.row.productId)">
                复制
              </el-button>
              <el-button @click="SingleListingDelist(scope.row.productId)">
                {{ findFrom.IsActive ? '下架' : '上架' }}
              </el-button>
              <el-button type="primary" @click="Redact(scope.row.productId)">
                编辑
              </el-button>
              <el-button v-if="scope.row.flag === 2 || scope.row.flag === 3 || scope.row.flag === 4" type="primary" @click="MemberProduct(scope.row.productId, scope.row.isScoreProduct)">
                {{ scope.row.isScoreProduct ? `编辑${scope.row.flag === 2 ? '积分' : '秒杀'}配置` : `添加${scope.row.flag === 2 ? '积分' : '秒杀'}配置` }}
              </el-button>
              <el-button v-if="scope.row.flag === 5" type="primary" @click="SkipPintuan(scope.row.productId)">
                拼团记录
              </el-button>
            </div>
          </template>
        </el-table-column>
      </ElTable>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('MerchandiseControl').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
    <el-dialog v-model="excelDialog" title="筛选" width="500">
      <el-form :model="excelForm">
        <div class="excel-dialog-css">
          <el-form-item label="上架时间" label-width="100">
            <el-date-picker
              v-model="excelForm.ActiveTime"
              type="datetimerange"
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item label="下单时间" label-width="100">
            <el-date-picker
              v-model="excelForm.OrderTime"
              type="datetimerange"
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="excelDialog = false">
            取消
          </el-button>
          <el-button type="primary" @click="GetExcel">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;
  }
}

.el-form-item {
  margin-bottom: 0;
}

.table-button {
  line-height: 42px;

  /* button {
    margin-bottom: 10px;
  } */
}
</style>
